#include "sslserver.h"
#include <QSslCertificate>

SSLServer::SSLServer(QObject *parent)
    :QTcpServer(parent)
{
#if 0
    QList<QSslCertificate> caCertList=QSslCertificate::fromPath("../certificates/cacert.pem");
    QSslSocket::setDefaultCaCertificates(caCertList);
#endif
}


void SSLServer::startService()
{
    qDebug()<<"listening";
    listen(QHostAddress::Any,9900);
}

void SSLServer::stopService()
{
    close();
}
void SSLServer::incomingConnection(int socketDescriptor)
{
    qDebug()<<"Server: incomingConnection:"<<socketDescriptor;
    SSLServerThread* thread=new SSLServerThread(socketDescriptor);
    //断开操作
    connect(thread,SIGNAL(socketDisconnected(int)),this,SLOT(serverThreadDisconnected(int)));
    //
    connect(thread,SIGNAL(finished()),this,SLOT(threadFinished()));
    connect(thread,SIGNAL(destroyed()),this,SLOT(threadDestroyed()));

    //remember to lock it
    serverThreadList.append(thread);
    thread->start();

}

void SSLServer::serverThreadDisconnected(int initSocketDescriptor)
{
    for(int i=0;i<serverThreadList.size();i++){
        if(serverThreadList.at(i)->getInitSocketDescriptor()==initSocketDescriptor){
            serverThreadList.at(i)->wait();
            delete serverThreadList.at(i);
            serverThreadList.removeAt(i);
            return;
        }
    }
}
void SSLServer::threadFinished()
{
    qDebug()<<"threadFinished";
}

void SSLServer::threadDestroyed()
{
    qDebug()<<"threadDestroyed";
}
